﻿using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using CityDashboard.Services;
using Newtonsoft.Json;

namespace CityDashboard.Services
{
    public class LocalDataService : ILocalDataService
    {
        public async Task SaveAsync<T>(T sourceData, string targetFileName)
        {
            var data = JsonConvert.SerializeObject(sourceData);
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(targetFileName,
                        CreationCollisionOption.ReplaceExisting);

            using (var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
            {
               await writer.WriteAsync(data);
            }            
        }

        public async Task<T> LoadAsync<T>(string sourceName)
        {
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sourceName,
                        CreationCollisionOption.OpenIfExists);
            using (var reader = new StreamReader(await file.OpenStreamForReadAsync()))
            {
                var source = await reader.ReadToEndAsync();
                if(!string.IsNullOrEmpty(source))
                    return JsonConvert.DeserializeObject<T>(source);
            }
            return default(T);
        }
    }
}
